package com.scott.masterselector.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @author Scott 2017/11/9 17:55
 */
public class MasterSelector {
    /**
     * zookeeper 连接字符串
     */
    private final static String CONNECT_STRING = "192.168.1.113:2181,192.168.11.104:2181";

    //master节点名称
    private final static String MASTER_PATH = "/master";

    public static void main(String[] args) {
        CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().connectString(CONNECT_STRING)
                .retryPolicy(new ExponentialBackoffRetry(1000,3)).build();

        LeaderSelector leaderSelector = new LeaderSelector(curatorFramework, MASTER_PATH, new LeaderSelectorListenerAdapter() {
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println("获取leader成功");
                TimeUnit.SECONDS.sleep(2);
            }
        });

        //竞争master
        leaderSelector.autoRequeue();
        leaderSelector.start();
    }
}
